import {view, BondViewGroup, binder} from "adajs";
import SettingService from "./state.js";
import User from './../../lib/user';
import File from "./../../lib/file";
import Loading from "./../../controls/loading";

@view({
    className: "settingc",
    template: "./template.html",
    style: "./style.scss",
    dataset: {
        service: SettingService
    }
})
class Setting extends BondViewGroup {
    @binder("gotoPage")
    gotoPage({item}) {
        this.dispatchEvent("gotoPage", item.link);
    }

    @binder("logout")
    logout() {
        this.context.request.post('/api/admin/user/logout').then(() => {
            User.clean();
            this.dispatchEvent("gotoPage", User.getUserMap().loginPath);
        });
    }

    @binder("change")
    change({e}) {
        let files = e.target.files || e.dataTransfer.files;
        let src = new File(files[0]).getFileURL();
        this.commit("setImage", src).then(() => {
            this.addChild(Loading).then(loading => {
                this.context.request.fetch({
                    url: "/api/resource/upload/uploadFile",
                    method: "post",
                    data: {file: files[0]}
                }).then(({code, data}) => {
                    if (code === '1') {
                        if (data.data[0]) {
                            this.context.request.post("/api/admin/sys/sysUserAdmin/updateUserProfile", {userView: data.data[0].encryptId}).then(({code}) => {
                                if (code === '1') {
                                    loading.showSuccess("修改头像成功");
                                    loading.close();
                                    this.finder("input").getElement.value = '';
                                } else {
                                    loading.showError('修改头像失败');
                                    loading.close();
                                    this.finder("input").getElement.value = '';
                                }
                            })
                        } else {
                            loading.showError('修改头像失败');
                            loading.close();
                            this.finder("input").getElement.value = '';
                        }
                    } else {
                        loading.showError('修改头像失败');
                        loading.close();
                        this.finder("input").getElement.value = '';
                    }
                })
            });
        });
    }
}

export default Setting;